import React, { useRef } from 'react';
import { useDrag, useDrop, XYCoord } from 'react-dnd';
import { DragItem, GridItem } from './types';

interface GridItemProps {
    item: GridItem;
    index: number;
    moveItem: (fromIndex: number, toIndex: number) => void;
}

const GridItemComponent: React.FC<GridItemProps> = ({ item, index, moveItem }) => {
    const ref = useRef<HTMLDivElement>(null);

    const [{ isDragging }, drag] = useDrag({
        type: 'GRID_ITEM',
        item: { index, id: item.id, type: 'GRID_ITEM' },
        collect: (monitor) => ({
            isDragging: monitor.isDragging(),
        }),
    });

    const [, drop] = useDrop({
        accept: 'GRID_ITEM',
        hover: (dragItem: DragItem, monitor) => {
            if (!ref.current) return;

            const dragIndex = dragItem.index;
            const hoverIndex = index;

            if (dragIndex === hoverIndex) return;

            const hoverBoundingRect = ref.current.getBoundingClientRect();
            const hoverMiddleX = (hoverBoundingRect.right - hoverBoundingRect.left) / 2;
            const clientOffset = monitor.getClientOffset();
            const hoverClientX = (clientOffset as XYCoord).x - hoverBoundingRect.left;

            // 只在鼠标超过一半时才移动
            // if (dragIndex < hoverIndex && hoverClientX < hoverMiddleX) return;
            // if (dragIndex > hoverIndex && hoverClientX > hoverMiddleX) return;

            moveItem(dragIndex, hoverIndex);
            dragItem.index = hoverIndex;
        },
    });

    drag(drop(ref));

    return (
        <div
            ref={ref}
            className={`grid-item ${isDragging ? 'dragging' : ''}`}
            style={{
                backgroundColor: item.color,
                opacity: isDragging ? 0.5 : 1,
                cursor: 'move',
            }}
        >
            <div className="item-content">
                <div className="item-id">{item.id}</div>
                <div className="item-text">{item.content}</div>
            </div>
        </div>
    );
};

export default GridItemComponent;